<?php

namespace App\Http\Middleware;

use App\Exceptions\ServiceException;
use App\Tools\Signature;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class H5Upload
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return Response
     * @throws ServiceException
     */
    public function handle(Request $request, Closure $next): Response
    {
        $params = $request->only(['scene','file_name','site_id','scan_tag','time','sign']);
        $log = [
            'params' => $params,
        ];
        Log::info('h5-upload-接收参数', $log);
        if (!array_key_exists('sign', $params)) {
            throw new ServiceException('sign does not exist !');
        }

        $sign = $params['sign'];
        unset($params['sign']);

        //校验签名过期时间
        if (Carbon::now()->diffInMinutes(Carbon::createFromTimestamp($params['time'])) > 3) {
            throw new ServiceException('sign expired !');
        }
        if (!$this->verify($params, $sign)) {
            Log::notice('h5-upload-验签失败', $log);

            throw new ServiceException('sign invalid !');
        }
        return $next($request);
    }

    public function generate(array $data): string
    {
        ksort($data);
        return md5(http_build_query($data, '', '&', PHP_QUERY_RFC3986));
    }

    public function verify($data, $sign): bool
    {
        return $this->generate($data) === $sign;
    }
}
